package services

import (
	"bankend/database"
	"bankend/models"
	"fmt"
	"strings"
	"time"
)

// UserService 用户服务
type UserService struct{}

// GetUsersFuzzy 根据查询参数模糊搜索用户（只返回未软删除记录）
func (s *UserService) GetUsersFuzzy(query string) ([]models.User, error) {
	var users []models.User
	db := database.DB
	if query != "" {
		pattern := "%" + strings.TrimSpace(query) + "%"
		err := db.Where("deleted_at IS NULL").
			Where("username LIKE ? OR full_name LIKE ? OR email LIKE ?", pattern, pattern, pattern).
			Find(&users).Error
		return users, err
	}
	err := db.Where("deleted_at IS NULL").Find(&users).Error
	return users, err
}

// GetUser 根据 ID 获取单个用户信息
func (s *UserService) GetUser(id int) (*models.User, error) {
	var user models.User
	err := database.DB.Where("user_id = ? AND deleted_at IS NULL", id).First(&user).Error
	if err != nil {
		return nil, fmt.Errorf("用户不存在")
	}
	return &user, nil
}

// CreateUser 创建新用户
func (s *UserService) CreateUser(user *models.User) error {
	// 开启事务
	tx := database.DB.Begin()

	// 设置创建和更新时间
	now := time.Now()
	user.CreateTime = now
	user.UpdateTime = now

	// 在事务中创建用户
	if err := tx.Create(user).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 创建用户订阅设置
	userSubscribe := models.UserSubscribe{
		UserID:          user.ID,
		SubscribeWeb:    false,
		SubscribeWechat: false,
	}

	if err := tx.Create(&userSubscribe).Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("创建用户订阅设置失败")
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return fmt.Errorf("提交事务失败")
	}

	return nil
}

// UpdateUser 更新用户信息
func (s *UserService) UpdateUser(id int, updated *models.User) error {
	user, err := s.GetUser(id)
	if err != nil {
		return err
	}

	updated.ID = user.ID
	updated.CreateTime = user.CreateTime
	updated.UpdateTime = time.Now()

	return database.DB.Model(user).Updates(updated).Error
}

// DeleteUser 软删除用户
func (s *UserService) DeleteUser(id int) error {
	now := time.Now()
	return database.DB.Model(&models.User{}).
		Where("user_id = ? AND deleted_at IS NULL", id).
		Update("deleted_at", now).Error
}